package ph.com.gs3.formalistics.model.facades;

import java.util.EnumSet;

import ph.com.gs3.formalistics.global.constants.UserUpdateOptions;
import ph.com.gs3.formalistics.model.LocalDataAccessObject.UpdateFailedException;
import ph.com.gs3.formalistics.model.ldao.UsersLDAO;
import ph.com.gs3.formalistics.model.vo.business.User;
import android.content.Context;

public class UsersDataWriter {

	private UsersLDAO usersLDAO;

	public UsersDataWriter(Context context) {
		usersLDAO = new UsersLDAO(context);
	}

	public User registerOrUpdateUser(User user) {
		return registerOrUpdateUser(user, EnumSet.of(UserUpdateOptions.UPDATE_ALL));
	}

	public User registerOrUpdateUser(User user, EnumSet<UserUpdateOptions> updateOptions) {

		usersLDAO.open();

		User registeredUser = null;
		User existingUser = usersLDAO.getUserWithWebAndCompanyId(user.getWebId(), user.getCompany()
		        .getId());

		if (existingUser == null) {
			// Save a new user
			registeredUser = usersLDAO.saveUser(user);
		} else {
			// Update the user using the new user's data
			int existingUserId = existingUser.getId();

			try {
				usersLDAO.updateUser(existingUserId, user, updateOptions);
				registeredUser = usersLDAO.getUserWithId(existingUserId);
			} catch (UpdateFailedException e) {
				// Unrecoverable error
				throw new RuntimeException(e);
			}
		}

		usersLDAO.close();

		return registeredUser;

	}
	
	public void deactivateCurrentlyActiveUser() {
		usersLDAO.open();
		usersLDAO.deactivateAllUsers();
		usersLDAO.close();
	}
}
